from dbutils.pooled_db import PooledDB
import pymysql
from utils.LogUtil import logger
from utils.iniUtil import IniUtil


class MysqlUtil:
    # 使用字典存储不同数据库的连接池
    _pools = {}

    def __init__(self, db_section="mysql_cgmodel_users"):
        if db_section not in MysqlUtil._pools:
            self._init_pool(db_section)
        self.conn = MysqlUtil._pools[db_section].connection()
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    @classmethod
    def _init_pool(cls, db_section):
        """初始化连接池"""
        try:
            data = IniUtil().read_settings_data()[db_section]

            cls._pools[db_section] = PooledDB(
                creator=pymysql,
                maxconnections=10,
                mincached=2,
                maxcached=5,
                maxshared=3,
                blocking=True,
                maxusage=None,
                setsession=[],
                ping=1,
                host=data["MYSQL_HOST"],
                port=int(data["MYSQL_PORT"]),
                user=data["MYSQL_USER"],
                passwd=data["MYSQL_PASSWORD"],
                db=data["MYSQL_DB"],
                charset='utf8mb4',
                autocommit=True
            )
            logger.info(f"MySQL连接池初始化成功: {db_section}")
        except Exception as e:
            logger.error(f"初始化MySQL连接池失败: {e}")
            raise

    def __del__(self):
        """释放资源"""
        try:
            if hasattr(self, 'cur'):
                self.cur.close()
            if hasattr(self, 'conn'):
                self.conn.close()
        except Exception as e:
            logger.error(f"释放数据库资源时出错: {e}")

    # 原有的查询方法保持不变
    def select_data_one(self, sql, params=None):
        try:
            logger.info(f"执行SQL: {sql}")
            self.cur.execute(sql, params or ())
            result = self.cur.fetchone()
            logger.info(f"SQL查询结果: {result}")
            return result
        except Exception as e:
            logger.error(f"SQL查询数据出错: {e}")
            raise

    def select_data_all(self, sql, params=None):
        try:
            logger.info(f"执行SQL: {sql} 参数: {params}")
            self.cur.execute(sql, params or ())
            result = self.cur.fetchall()
            logger.info(f"SQL查询结果: {result}")
            return result
        except Exception as e:
            logger.error(f"SQL查询数据出错: {e}")
            raise

    def execute_db_data(self, sql, params=None):
        try:
            logger.info(f"执行SQL: {sql} 参数: {params}")
            self.cur.execute(sql, params or ())
            self.conn.commit()
            return self.cur.rowcount
        except Exception as e:
            logger.error(f"执行SQL出错: {e}")
            self.conn.rollback()
            raise


if __name__ == '__main__':
    db = MysqlUtil("mysql_cgmodel_model")
   # res = db.select_data_one("select code from users_verifycode where mobile = '15555556666' order by id desc limit 1")
    res = db.select_data_one("select * from cgmodel_model where user_id=1164638 order by id desc")
    print(res)

    db = MysqlUtil("mysql_cgmodel_works")
    res = db.select_data_one("select * from cgmodel_works where user_id=1164638 order by id desc")
    print(res)
    # res2 = db.execute_db_data("delete from users_userprofile where mobile = '18898988989'")
